
var cf = require("../config.js");
var Ce = [{
  html: /(&ensp;|&emsp;|&nbsp;)/gi,
  value: " "
}, {
  html: /&quot;/gi,
  value: '"'
}, {
  html: /&lt;/gi,
  value: "<"
}, {
  html: /&gt;/gi,
  value: ">"
}];
function chageChatData2(e) {
  var t = e;
  return Ce.forEach(function (e) {
    t = t.replace(e.html, e.value);
  }), t;
}
/*金钱格式化*/
function fenToYuan(num) {
  if (isNaN(num)) {
    num = 0;
  }
  return parseFloat(parseFloat(num) / 100).toFixed(2);
}
/*时间---年月日时分秒格式化*/
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
/*时间--年月日格式化*/
function formatDate(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  return [year, month, day].map(formatNumber).join('-');
}
/*年月日格式化*/
function formatDateC(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  return year + "年" + month + "月" + day + "日";
}
/*字符串格式化*/
function formatNumber(n) {
  n = n.toString();
  return n[1] ? n : '0' + n
}
/*数字增0格式化*/
function numAddPreZero(num) {
  if (isNaN(num)) {
    return 0;
  } else {
    num = parseInt(num);
    return num >= 10 ? num : "0" + num;
  }


}
/*订单状态格式化*/
function getOrderStatus(order, siteType) {//商店类型，如预约：yuyue
  var status = order.orderStatus;
  var orderType = order.orderType;
  if (status == 1) {
    return "待支付";
  } else if (status == 2) {
    if (orderType == 2) {
      return "待配送";
    } else {
      return siteType == "yuyue" ? "待消费" : "待发货";
    }
  } else if (status == 3) {
    if (orderType == 2) {
      return "已配送";
    } else {
      return siteType == "yuyue" ? "待确认" : "待收货";
    }
  } else if (status == 4) {
    return "交易完成";
  } else if (status == 5) {
    return "已取消";
  } else if (status == 6) {
    return "已退货";
  } else if (status == 7) {
    return "待发货，退货中";
  } else if (status == 8) {
    return "已发货，退货中";
  } else if (status == 9) {
    return "已完成，退货中";
  } else if (status == 10) {
    return "待接单";
  }
}
//获取购物车数量
function getShoppingCartCount(cb, app) {
  var cusmallToken = wx.getStorageSync('cusmallToken');
  wx.request({
    url: cf.config.pageDomain + '/applet/mobile/visitcard/shopCart/getCartCount',
    data: {
      cusmallToken: cusmallToken,
      fromUid: app.globalData.fromuid || "",
      shopUid: app.globalData.shopuid || ""
    },
    header: {
      'content-type': 'application/json'
    },
    success: function (res) {
      if (res.data.ret == 0) {
        typeof cb == "function" && cb(res.data.model.result);
      }

    }
  })
}
/**
 * 解析QQ视频链接的源地址
 * 目前支持这几种链接类型：
 * 1、https://imgcache.qq.com/tencentvideo_v1/playerv3/TPout.swf?max_age=86400&v=20161117&vid=x0565vkatl1&auto=0
 * 2、https://v.qq.com/x/cover/dk6z4x5v536r3fz.html
 * 3、https://v.qq.com/iframe/player.html?vid=g0024nmxe2z&tiny=0&auto=0
 */
function getQQVideoInfo(item, i, cb) {
  try {
    var linkUrl = item.data.url;
    var patt = /v.qq.com|imgcache.qq.com/g;
    if (!patt.test(linkUrl)) {
      return false;
    }
    var srcPatt = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
    var embedPatt = /<\/embed>|<\/iframe>/g;
    if (embedPatt.test(linkUrl)) {
      var src = linkUrl.match(srcPatt);
      if (src.length == 2) {
        linkUrl = src[1];
      } else {
        return false;
      }
    }
  } catch (e) {
    console.log(e);
  }

  wx.request({
    url: cf.config.pageDomain + '/applet/mobile/video_analysis/analysis',
    data: {
      origUrl: linkUrl || ""
    },
    header: {
      'content-type': 'application/json'
    },
    success: function (res) {
      if (res.data.ret == 0) {
        typeof cb == "function" && cb(item, i, res.data.model.url);
      }
    }
  })
}

// 统计PV流量
function addPVStat(cb) {
  var cusmallToken = wx.getStorageSync('cusmallToken');
  wx.request({
    url: cf.config.pageDomain + '/applet/mobile/dataStatistics/addPv',
    data: {
      cusmallToken: cusmallToken
    },
    header: {
      'content-type': 'application/json'
    },
    success: function (res) {
      typeof cb == "function" && cb(res.data.model.count);
    }
  })
}

// 处理控件中链接类型的转换
function convertItemLink(item, page) {
  var app = page.data.app;
  var shopuid = app.globalData.shopuid;
  var fromuid = app.globalData.fromuid;
  if (item && item.link_type) {
    if (item.link_type == 1) {
      item.url = "test";
    } else if (item.link_type == 8) {
      item.url = "/pages/index/index";
      if (shopuid) {
        item.url = item.url + "?shopuid=" + shopuid;
        if (fromuid) {
          item.url = item.url + "&fromuid=" + fromuid;
        }
      }
    } else if (item.link_type == 9) {
      item.url = item.url;
    } else if (item.link_type == 10) {
      item.url = item.url;
    } else if (item.link_type == 13) {
      item.url = "/pages/subCategory/subpage?pageId=" + item.pageid;
    } else if (item.link_type == 15) {
      item.url = "/pages/category/category";
      if (item.style) {
        item.url = "/pages/category/category?style=" + item.style;
      }
    } else if (item.link_type == 16) {
      item.url = "/pages/shoppingcar/shoppingcar";
    } else if (item.link_type == 17) {
      item.url = "/pages/uniquecenter/uniquecenter";
    } else if (item.link_type == 18) {
      item.url = "tel:" + item.link_telnum;
    } else if (item.link_type == 19) {
      item.url = "lbs:" + item.pageid + ":" + item.style + ":" + item.link_name;
      // if (app.globalData.previewuid){
      //   item.url = "lbs:uid:" + app.globalData.previewuid;
      // }
      // if (app.globalData.shopuid){
      //   item.url = "lbs:uid:" + app.globalData.shopuid;
      // }

    } else if (item.link_type == 20) {
      item.link_appid = item.link_appid || item.url;
      item.url = "miniapp:" + item.link_appid;
      // item.target = "miniProgram";

    }  else if (item.link_type == 21) {
      item.url = "/pages/takeout/index?type=ta";
    } else if (item.link_type == 22) {
      if (shopuid) {
        item.url = "tips:offline";
      }
      item.url = "/pages/offline/pay?id=" + item.pageid;
    } else if (item.link_type == 23) {
      item.url = item.url;
    } else if (item.link_type == 24) {
      item.url = "/pages/shopping_mall/coupon/coupon?id=" + item.pageid;
    } else if (item.link_type == 25) {
      item.url = "/pages/groupbuy/groupbuy?activityId=" + item.pageid;
      if (shopuid) {
        item.url = "tips:mulshop";
      }
    } else if (26 == item.link_type) {
      item.url = "/pages/shopping_mall/sbargain/sbargain?activityId=" + item.pageid;
      if (shopuid) {
        item.url = "tips:mulshop";
      }
    } else if (27 == item.link_type) {
      item.url = "/pages/mult/multlist?id=" + item.pageid;
    } else if (28 == item.link_type) { //传入板块id
      item.url = "/pages/forum/community?plateId=" + item.pageid;
      if (shopuid) {
        //item.url = "tips:forum";
      }
    } else if (item.link_type == 30) {
      item.url = "/pages/takeout/index?type=tostore";
    } else if (item.link_type == 31) {
      if (item.pageid) {
        item.url = "/pages/subCategory/sCategoryList?clsid=" + item.pageid + "&clsname=" + item.link_name;
      } else {
        item.url = "/pages/subCategory/subCategory";
      }

    } else if (item.link_type == 32) {
      // item.url = "/pages/backuppage/backup1";
    } else if (item.link_type == 33) {
      item.url = "/pages/uniquecenter/sign";
    } else if (item.link_type == 34) {
      item.url = "/pages/index/index?" + item.pageid;
    } else if (item.link_type == 35) {
      item.url = "/pages/sbargain/seckillGoods?id=" + item.pageid;
    } else if (item.link_type == 36) {
      item.url = "/pages/interaction/wheel/wheel?activityId=" + item.pageid;
    } else if (37 == item.link_type) {
      item.url = "/pages/interaction/kouling/pack_send/pack_send";
    } else if (38 == item.link_type) {
      item.url = "/pages/interaction/golden_egg/golden_egg?activityId=" + item.pageid;
    } else if (39 == item.link_type) {
      item.url = "/pages/interaction/shake_tree/shake_tree?activityId=" + item.pageid;
    } else if (40 == item.link_type) {
      item.url = "/pages/interaction/heartbeatmatch/heartbeatmatch?activityId=" + item.pageid;
    } else if (41 == item.link_type) {
      item.url = "/pages/interaction/xiuyixiu/xiuyixiu?activityId=" + item.pageid;
    } else if (42 == item.link_type) {
      item.url = "/pages/interaction/zqjizi/zqjizi?activityId=" + item.pageid;
    } else if (43 == item.link_type) {
      if (item.pageid) {

        item.url = "/pages/forum/community?plateId=" + item.pageid;
      } else {
        item.url = "/pages/forum/communityPlate";
      }

    } else if (44 == item.link_type) {
      item.url = "/pages/interaction/guaguaka/guaguaka?activityId=" + item.pageid;
    } else if (45 == item.link_type) {//多媒体文件
      item.url = "/pages/multMedia/multMediaDetail?id=" + item.pageid;
    } else if (46 == item.link_type) {//多媒体分组
      item.url = "/pages/multMedia/mMediaList?id=" + item.pageid;
    } else if (47 == item.link_type) {//排号
      item.url = "/pages/queue/queueList";
    } else if (48 == item.link_type) {// WIFI
      item.url = "wifi:" + item.link_wifiinfo;
    } else if (49 == item.link_type) {// WIFI
      item.url = "/pages/secondCard/cardList";
    } else if (50 == item.link_type) {
      item.url = "/pages/articlelink/articlelink?articleUrl=" + item.link_articleUrl;
    } else if (item.link_type == 51) {
      item.url = "/pages/shopping_mall/group_book/groupbuy?activityId=" + item.pageid;
    } else if (52 == item.link_type) {
      //item.url = "/pages/mall/goods_list";
    } else if (53 == item.link_type) {
      item.url = "/pages/blessing/index/index";
    } else {
      item.url = item.url;
    }
  } else {
    item.url = "blank";
  }
  return item;
}
/*图片格式化*/
function formatImg(html) {
  var newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
    var classReg = new RegExp(/class=['|\"]([^\'\"]*)['|\"]/i);
    var styleReg = new RegExp(/style=['|\"]([^\'\"]*)['|\"]/i);
    var srcReg = new RegExp(/src=['|\"]([^\'\"]*)['|\"]/i);

    // 添加压缩图片参数
    if (srcReg.test(match)) {
      match = match.replace(srcReg, function (m, captrue) {
        var slimParam = (m.indexOf("?") != -1 ? "|" : "?") + "imageView2/2/w/1080";
        return m.substring(0, m.length - 1) + slimParam + m.substring(m.length - 1);
      });
    }
    if (styleReg.test(match)) {
      match = match.replace(styleReg, function (m, captrue) {
        return m.substring(0, m.length - 1) + " max-width:100%; display: block;" + m.substring(m.length - 1);
      });
    }
    if (classReg.test(match)) {
      match = match.replace(classReg, function (m, captrue) {
        return m.substring(0, m.length - 1) + " img-responsive" + m.substring(m.length - 1);
      });
    } else {
      var srcIndex = match.indexOf("src=");
      return match.substring(0, srcIndex) + " class='img-responsive' " + match.substring(srcIndex);
    }
    return match;
  });
  return newContent;
}

// 处理模板数据（初始化富文本插件，商家金额除以100取小数点2位）
function processDecorationData(decorationData, page, decorationLocation) {
  var bannerIndex = 0;
  var multClassArr = [];
  var communityFirst = true;
  var hasLoadAllCategory = false;
  var hasLoadAllSubCls = false;
  if (getApp().globalData.bottomMenus) {
    getApp().globalData.bottomMenus.isShow = false;
  }

  // 刷新页面后清除原来的定时器
  if (page.data.decoration && page.data.decoration.items) {
    for (let i = 0; i < page.data.decoration.items.length; i++) {
      let item = page.data.decoration.items[i];
      if (item.item_type == "announceWidget") {
        if (item.data.scrollTimer) {
          clearInterval(item.data.scrollTimer);
        }
      }
    }
  }

  //getApp().globalData.bottomMenus = null;
  if (decorationData != null && decorationData.items != null) {
    for (var i = 0; i < decorationData.items.length; i++) {
      var item = decorationData.items[i];
      if (item.item_type == "mc_goodslist") {
        // var goodsList = item.data.list;
        // for(var j=0;j<goodsList.length;j++){
        //   var goods = goodsList[j];
        //   goods.price = (goods.price/100).toFixed(2);
        // }
      } else if (item.item_type == "richtext") {
        if (item.data.richtext) {
          // 富文本图片宽度自适应
          item.data.richtext = formatImg(item.data.richtext);
        }
      } else if (item.item_type == "title") {
        convertItemLink(item.data, page);
      } else if (item.item_type == "img_ad") {
        item.item_index = bannerIndex;
        bannerIndex++;
        var itemList = item.data.list;
        for (var j = 0; j < itemList.length; j++) {
          convertItemLink(itemList[j], page);
        }
      } else if (item.item_type == "bottomMenusWidget") {
        // var itemList = item.data.list;
        // for (var j = 0; j < itemList.length; j++) {
        //   convertItemLink(itemList[j], page);
        // }
        // getApp().globalData.bottomMenus = item.data;
      } else if (item.item_type == "microBottomMenusWidget") {
        var itemList = item.data.list;
        for (var j = 0; j < itemList.length; j++) {
          convertItemLink(itemList[j], page);
        }
      } else if (item.item_type == "img_nav" ||
        item.item_type == "two_box" ||
        item.item_type == "three_box" ||
        item.item_type == "four_box" ||
        item.item_type == "text_nav" ||
        item.item_type == "showcaseWidget" ||
        item.item_type == "listWidget") {
        var itemList = item.data.list;
        for (var j = 0; j < itemList.length; j++) {
          convertItemLink(itemList[j], page);
        }
      } else if (item.item_type == "videoWidget") {
        (function (decorationLocation) {
          getQQVideoInfo(item, i, function (item, i, url) {
            item.data.url = url;
            if (decorationLocation) {
              page.setData({
                [decorationLocation + '.items[' + i + ']']: item
              });
            } else {
              page.setData({
                ['decoration.items[' + i + ']']: item
              });
            }
          });
        })(decorationLocation)
      } else if (item.item_type == "announceWidget") {
        let itemList = item.data.list;
        for (let j = 0; j < itemList.length; j++) {
          convertItemLink(itemList[j], page);
        }
        // 公告组件上下滚动定时器
        if (item.data.direction == "v" && item.data.list.length > 1) {
          item.data.marginTop = 0;
          let itemHeight = (item.data.height || 25);
          (function (item, i, decorationLocation) {
            item.data.scrollTimer = setInterval(function () {
              if (item.data.marginTop == -(item.data.list.length - 1) * itemHeight) {
                item.data.marginTop = 0;
              } else {
                item.data.marginTop -= itemHeight;
              }
              if (decorationLocation) {
                page.setData({
                  [decorationLocation + '.items[' + i + ']']: item
                });
              } else {
                page.setData({
                  ['decoration.items[' + i + ']']: item
                });
              }
            }, 4000);
          })(item, i, decorationLocation);
        }
      } else if (item.item_type == "categoryTabWidget") {
        if (!hasLoadAllCategory) {
          page.loadAllCategory(i);
          hasLoadAllCategory = true;
        }
      } else if (item.item_type == "nav_tab_panel") {
        let itemList = item.data.list;
        if (itemList && itemList.length > 0) {
          page.loadNavPanelPageContent(i, 0, itemList[0].pageid);
        }
      } else if ("subPageWidget" == item.item_type) {
        // if (!hasLoadAllSubCls) {
        //   page.findAllSubCls(i);
        //   hasLoadAllSubCls = true;
        // }
      } else if ("informationWidget" == item.item_type) {
        if (item.data.list.length > 0 && item.data.list[0].pageid) {
          let infoPageList = [];
          for (let i = 0; i < item.data.list.length; i++) {
            infoPageList.push({ "id": item.data.list[i].pageid });
          }
          page.loadInfoPageById(item.data.list[0].pageid);
          page.setData({
            selectedInfoPageId: item.data.list[0].pageid,
            selectedInfoPageIdx: 0,
            infoPageList: infoPageList
          })
        }
      }  else if (item.item_type == "search") {
        page.setData({
          haveSearch: true
        })
      } else if (item.item_type == "bgMusicWidget") {
        page.setData({
          bgMusic: item.data.music
        })
      } else if ("freeWidget" == item.item_type) {
        item.data.hDivW = item.data.height / item.data.constwidth;//constwidth因为自由面板的宽 在pc是固定的
        item.data.calHeight = item.data.hDivW * wx.getSystemInfoSync().windowWidth;
        let mWidgets = item.data.widgets;
        for (let i = 0; i < mWidgets.length; i++) {
          mWidgets[i].data.calWidth = parseInt(mWidgets[i].data.width) / item.data.constwidth * wx.getSystemInfoSync().windowWidth;
          mWidgets[i].data.calHeight = parseInt(mWidgets[i].data.height) / parseInt(mWidgets[i].data.width) * mWidgets[i].data.calWidth;
          convertItemLink(mWidgets[i].data, page);
        }

      } else if ("imgWidget" == item.item_type) {
        autoCalcImgAndBtnWidget(item);
        convertItemLink(item.data, page);
      } else if ("btnWidget" == item.item_type) {
        autoCalcImgAndBtnWidget(item);
        convertItemLink(item.data, page);
      } else if ("seckillWidget" == item.item_type) {
        if (undefined == page.data.seckList) {
          page.setData({
            seckList: []
          })
          page.getSKListData();
        }
      } else if (item.item_type == "groupbuyWidget") {
        if (item.data.activityId) {
          page.groupbuyHandle.fetchGroupbuyData(page, item.data.activityId)
        }
        //砍价
      } else if (item.item_type == "sbargainWidget") {
        if (item.data.activityId) {
          page.sbargainHandle.fetchSbargainData(page, item.data.activityId)
        }
      }
    }
  }

  page.setData({
    multClassArr: multClassArr
  })
}

// 所有页面onLoad方法执行完成后的回调方法
function afterPageLoad(page) {
  // 自定义底部菜单数据，计算当前页面是否需要显示底部菜单，计算哪个菜单项是选中状态

  var currentPage = getCurrentPages()[getCurrentPages().length - 1].route;
  var menusList = page.data.botMenus && page.data.botMenus.list || [];
  // menusList[1].pagePath = "pages/mall/goods_list";
  // menusList[2].pagePath = "pages/shopping_mall/index/index";

  console.log(currentPage)
  for (let val of menusList){
    if (currentPage === val.pagePath){
      val.sel = true;
    }else{
      val.sel = false;
    }
  }
  page.setData({ ['botMenus.list']: menusList });
}

// 处理订单数据（时间格式转换）
function processOrderData(orderData) {
  if (orderData.buyTime) {
    orderData.buyTime = formatTime(new Date(orderData.buyTime));
  }
  if (orderData.createTime) {
    orderData.createTime = formatTime(new Date(orderData.createTime));
  }
  if (orderData.payTime) {
    orderData.payTime = formatTime(new Date(orderData.payTime));
  }
  if (orderData.realDeliveryTime) {
    orderData.realDeliveryTime = formatTime(new Date(orderData.realDeliveryTime));
  }
}

// 处理banner高度根据image高度自适应
function processBannerImgLoad(e, page) {
  var w = e.detail.width;
  var h = e.detail.height;
  var bannerIndex = e.currentTarget.dataset.bannerindex;
  var bannerHeight = (h / w) * 750;
  if (!page.data.bannerHeight[bannerIndex] || bannerHeight > page.data.bannerHeight[bannerIndex]) {
    page.data.bannerHeight[bannerIndex] = bannerHeight;
    page.setData({ bannerHeight: page.data.bannerHeight });
  }

}

// 处理页面navigate点击事件
function processNavClick(e) {
  var url = e.currentTarget.dataset.url;
  var isIndexPage = e.currentTarget.dataset.isindexpage;
  var isFooterTab = e.currentTarget.dataset.isfootertab;
  var isBtn = e.currentTarget.dataset.isbtn;
  if (!url) {
    return false;
  }
  
  if (url.indexOf("tel:") == 0) {
    // 拨打电话
    wx.makePhoneCall({
      phoneNumber: url.split(":")[1]
    })
  } else if (url.indexOf("miniapp:") == 0) {
    //打开其他小程序
    wx.navigateToMiniProgram({
      appId: url.split(":")[1],
      success(res) {
        // 打开成功
      },
      fail(res) {
        wx.showModal({
          title: "提示",
          content: "没有该小程序",
          showCancel: false
        });
      }
    })
  } else if (url.indexOf("wifi:") == 0) {
    var url = e.currentTarget.dataset.url;
    let wifiInfo = url.split(":")[1];
    if (wifiInfo) {
      let wifiConfig = wifiInfo.split(";");
      wx.showLoading({
        title: '连接中...',
      });
      wx.startWifi({
        success: function (res) {
          wx.connectWifi({
            SSID: wifiConfig.length >= 1 ? wifiConfig[0] : "",
            BSSID: wifiConfig.length >= 2 ? wifiConfig[1].split(",").join(":") : "",
            password: wifiConfig.length >= 3 ? wifiConfig[2] : "",
            success: function (res) {
              wx.showModal({
                title: "提示",
                content: "wifi连接完成！",
                showCancel: false
              });
            },
            fail: function (res) {
              wx.showModal({
                title: "提示",
                content: "wifi连接失败：" + res.errMsg,
                showCancel: false
              });
              console.log(res.errMsg)
            },
            complete: function () {
              wx.hideLoading();
            }
          })
        }
      })
    } else {
      wx.showModal({
        title: "提示",
        content: "wifi连接无效，请检查配置信息",
        showCancel: false
      });
    }
  } else if (url.indexOf("miniapp:") == 0) {
    // 打开其他小程序
    // wx.navigateToMiniProgram({
    //   appId: url.split(":")[1],
    //   success(res) {
    //     // 打开成功
    //   }
    // })
  } else if (url.indexOf("tips:") == 0) {
    var tipsType = url.split(":")[1];
    if ("mulshop" == tipsType) {
      wx.showModal({
        title: '温馨提示',
        content: "子店铺不参与连锁店铺活动，如有疑问请联系商家！"
      })
    } else if ("offline" == tipsType) {
      wx.showModal({
        title: '温馨提示',
        content: "子店铺不支持当面付，如有疑问请联系商家！"
      })
    } else if ("forum" == tipsType) {
      wx.showModal({
        title: '温馨提示',
        content: "子店铺不支持社区，如有疑问请联系商家！"
      })
    } else if (tipsType) {
      wx.showModal({
        title: '温馨提示',
        showCancel: false,
        content: tipsType
      })
    }
    return;
  } else if (url.indexOf("lbs:") == 0) {
    // 打开地图
    var latLng = url.split(":")[1];
    var addr = url.split(":")[2];
    var name = url.split(":")[3];
    wx.openLocation({
      latitude: Number(latLng.split(",")[0]),
      longitude: Number(latLng.split(",")[1]),
      scale: 28,
      name: name,
      address: addr
    })

    // var extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {}
    // var lbsType = url.split(":")[1];
    // var uid = extConfig.uid;
    // if (url.split(":").length == 3){
    //   uid = url.split(":")[2];
    // }
    // if("uid" == lbsType){
    //   wx.showLoading({
    //     title: '加载中',
    //   });

    //   wx.request({
    //     url: cf.config.pageDomain + '/applet/mobile/lbsinfo/getLbsInfo',
    //     data: {
    //       uid: uid
    //     },
    //     header: {
    //       'content-type': 'application/json'
    //     },
    //     success: function (res) {
    //       if (res.data.ret == 0) {
    //         console.log(res.data);
    //         var lbsinfo = res.data.model.lbsinfo;
    //         wx.openLocation({
    //           latitude: Number(lbsinfo.latitude),
    //           longitude: Number(lbsinfo.longitude),
    //           scale: 28,
    //           name: lbsinfo.name,
    //           address:lbsinfo.address
    //         })
    //         wx.hideLoading();
    //       } else {
    //         wx.hideLoading();
    //         wx.showModal({
    //           title: '获取LBS信息异常',
    //           showCancel: false,
    //           content: res.data.msg
    //         })
    //       }
    //     }
    //   });
    // }
  } else {
    if (isFooterTab && !isIndexPage) {
      // if ("/pages/index/index" == url) {
      //   wx.reLaunch({
      //     url: url,
      //   });
      // }else{
      //    wx.redirectTo({
      //      url: url,
      //    });
      // }

    } else if (isBtn) {
      wx.navigateTo({
        url: url,
      });
    }
  }
  return true;
}
//drawEle[
//{type:"",x:100,y:100,width:100,height:100,url:"",fontSize:10,color:"#333333",text:""}
//]
//type 需要画的元素 支持img （图片）、 txt（文字）、dashLine（虚线）
//x 横坐标位置 y纵坐标位置  width 元素的宽 元素的高height   fontSize 字体大小 color 字体颜色/线条颜色 text 文字内容
//
function drawPoster(cxt, drawEle, drawWidth, drawHeight, callback) {
  drawPostDetail(cxt, drawEle, 0, drawWidth, drawHeight, callback);
}

function drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback) {
  if (idx == drawEle.length) {
    cxt.draw();
    setTimeout(function () {
      callback();
    }, 400)
    return;
  }
  let ele = drawEle[idx++]
  switch (ele.type) {
    case "img":
      wx.downloadFile({
        url: ele.url,
        success: function (res) {
          cxt.drawImage(res.tempFilePath, ele.x, ele.y, ele.width, ele.height);
        },
        fail: function (e) {
          console.log(e)
        },
        complete: function () {
          console.log("com " + (idx - 1));
          drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
        }
      });
      break;
    case "txt":
      cxt.setFillStyle(ele.color);
      cxt.setFontSize(ele.fontSize);
      cxt.fillText(ele.text, ele.x, ele.y);
      drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
      break;
    case "dashLine":
      cxt.setLineWidth(1)
      cxt.setStrokeStyle(ele.color);
      cxt.beginPath();
      cxt.setLineDash([4, 2]);
      cxt.moveTo(ele.x, ele.y);
      cxt.lineTo(ele.toX, ele.toY);
      cxt.stroke();
      drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
      break;
    case "base64Img":
      wx.downloadFile({
        url: ele.url,
        success: function (res) {
          cxt.drawImage(res.tempFilePath, ele.x, ele.y, ele.width, ele.height);
          console.log("suc " + (idx - 1));
        },
        fail: function (e) {
          console.log(e)
        },
        complete: function () {
          console.log("com " + (idx - 1));
          drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
        }
      });
      break;
    case "rect":
      cxt.setFillStyle(ele.color);
      cxt.fillRect(ele.x, ele.y, ele.width, ele.height);
      drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
      break;
  }
}
function tinyWxHeadImg(headImg) {
  if (headImg == null) return "";
  var headLength = headImg.length;
  if (headImg.substring(headLength - 2, headLength) == "/0") {
    headImg = headImg.substring(0, headLength - 2) + "/96";
  }
  return headImg;
}
function autoGeyAddr(callback, cusmallToken) {
  wx.getLocation({
    type: 'gcj02',
    success: function (res) {
      wx.request({
        url: cf.config.pageDomain + "/applet/mobile/map_api/locationToDesc",
        data: {
          cusmallToken: cusmallToken,
          location: res.latitude + "," + res.longitude
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          let data = res.data;
          callback(data)

        },
        fail: function () {
        },
        complete: function () {
        }
      });

    }
  });
}

function myPXToRPX(val) {
  val = parseFloat(val);
  return 750 / wx.getSystemInfoSync().windowWidth * val;
}

function autoCalcImgAndBtnWidget(item) {
  let numWidth = parseInt(item.data.width);
  let numHeight = parseInt(item.data.height);
  item.data.hDivW = numHeight / numWidth;
  item.data.calWidth = numWidth / item.data.constwidth * wx.getSystemInfoSync().windowWidth;
  item.data.calHeight = item.data.calWidth * item.data.hDivW;
}

function phoneValidate(str) {
  let validate = /^1[2|3|4|5|6|7|8|9][0-9]\d{4,8}$/;
  return validate.test(str);
}
function cusSubString(str,max){
  if (str && str.length > max){
    return str.substring(0,max) + "...";
  }else{
    return str;
  }
}

function getCardSource(i){
  i  = parseInt(i);
  switch (i) {
    case 0:
      return "扫描";
    case 1:
      return "分享";
    case 2:
      return "搜索";
    case 3:
      return "人工转入";
    default:
      return "--";
  }
}

// 获取场景值信息
function fetchSceneInfo(scene, cb) {
  wx.request({
    url: cf.config.pageDomain + '/applet/mobile/verifiedclerk/findSceneEntity',
    data: {
      scene: scene
    },
    header: {
      'content-type': 'application/json'
    },
    success: function (res) {
      if (res.data.ret == 0) {
        cb && cb(res)
      } else {
        wx.showModal({
          title: '获取场景信息异常',
          showCancel: false,
          content: res.data.msg
        })
      }
    }
  })
}

function behaviorType(num, count){
  switch (num) {
    case 1:
      return {
        action: "点赞",
        target:"名片"
      };
    case 2: 
      if (4 < count){
        return {
          action: "查看",
          target: "名片",
          desc:"，强意向客户哟"
        };
      }else{
        return {
          action: "查看",
          target: "名片",
          desc: "，你的潜在客户出现了"
        };
      }
    
    case 3:
      return {
        action: "转发",
        target: "名片",
        desc:"，你的人脉圈正在裂变"
      };
    case 4:
      return {
        action: "查看",
        target: "商品"
      };
    case 5:
      return {
        action: "转发",
        target: "商品"
      };
    case 6:
      return {
        action: "购买",
        target: "商品"
      };
    case 7:
      return {
        action: "查看",
        target: "官网"
      };
    case 8:
      return {
        action: "查看",
        target: "商城",
        desc:"，请及时把握商机"
      };
    case 9:
      return {
        action: "复制",
        target: "微信"
      };
    case 10:
      return {
        action: "复制",
        target: "邮箱"
      };
    case 11:
      return {
        action: "拨打",
        target: "电话"
      };
    case 12:
      return {
        action: "保存",
        target: "电话",
        desc:"，可以考虑拜访"
      };
    case 13:
      return {
        action: "查看",
        target: "动态"
      };
    case 14:
      return {
        action: "评论",
        target: "动态"
      };
    case 15:
      return {
        action: "点赞",
        target: "销售员标签"
      };
    case 16:
      return {
        action: "点击",
        target: "咨询"
      };
    case 17:
      return {
        action: "提交",
        target: "表单"
      };
    case 18:
      return {
        action: "点赞",
        target: "动态"
      };
    case 19:
      return {
        action: "评论",
        target: "公司动态"
      };
    case 20:
      return {
        action: "点赞",
        target: "公司动态"
      };
    default:
      return "";
  }
}
//增加行为轨迹

function addBehaviorTrail(eid, mType, businessId, sttr1, sttr2,sttr3){
  var cusmallToken = wx.getStorageSync('cusmallToken');
  var userId = wx.getStorageSync('userId')
  console.log("addBehaviorTrail --- before ---", eid, mType)
  wx.request({
    url: cf.config.pageDomain + '/applet/mobile/visitcard/bahavior/addBehaviorTrail',
    data: {
      accountId:userId,
      cusmallToken: cusmallToken,
      eid: eid,
      "type": mType,
      businessId: businessId || "",
      sttr1: sttr1 || "",
      sttr2: sttr2 || "",
      sttr3: sttr3 || "",
    },
    method: "POST",
    header: { "Content-Type": "application/x-www-form-urlencoded" },
    success: function (res) {
      console.log("addBehaviorTrail --- done");
      console.log(res.data)
    }
  })
}

//用户绑定名片
function addRelation(employeeId, cusmallToken,source, cb) {
  //选择默认联系人
  console.log(employeeId, "----", source)
  wx.request({
    url: cf.config.pageDomain + "/applet/mobile/visitcard/memberrelation/addRelation",
    data: {
      cusmallToken: cusmallToken,
      employeeId: employeeId,
      source: source,
    },
    header: {
      'content-type': 'application/json'
    },
    success: function (res) {
      var data = res.data;
    },
    fail() {
    },
    complete() {
    }
  })
}

function previewImageHkt(idx, imgs){
  
  for (let i in imgs) {
    imgs[i] = cf.config.userImagePath + imgs[i];
  }
  
  wx.previewImage({
    current: imgs[idx], // 当前显示图片的http链接
    urls: imgs // 需要预览的图片http链接列表
  })
}
function timestampToDayHkt(createTime){
  var timestamp = Date.now() - createTime;
  var day = 0;
  if (0 >= timestamp) {
    return "刚刚";
  }

  if (432000000 < timestamp){
    return formatTime(new Date(createTime));
  }

  if (60 > timestamp / 1000) {//seconds
    day ="刚刚";
  } else if (60 > timestamp / 1000 / 60) {//min
    day = Math.floor(timestamp / 1000 / 60) + "分钟前";
  } else if (24 > timestamp / 1000 / 60 / 60) {//hours
    day = Math.floor(timestamp / 1000 / 60 / 60) + "小时前";
  } else {
    day = Math.floor(timestamp / 86400000) + "天前";
  }

  
  return day;
}

// 检查token的缓存是否过期
function removeTokenIfExpired(){
  if (!wx.getStorageSync('lastTokenTime')) {
    wx.removeStorageSync("cusmallToken");
  } else {
    let lastTokenTime = wx.getStorageSync('lastTokenTime');
    // token 默认两天后失效
    if (new Date().getTime() - lastTokenTime > 2 * 24 * 60 * 60 * 1000) {
      wx.removeStorageSync("cusmallToken");
    }
  }
}

//计时器类
class TimerClass {
  constructor(totalCount = 60, cbk = null) {
    this.totalCount = Number(totalCount) + 1
    this.cbk = cbk
    this._reset({ totalCount, cbk })
  }

  _reset() {
    this.timer && clearTimeout(this.timer)
    this.timer = null
    this.disabled = false
    this.currentCount = this.totalCount
    this.countText = '获取验证码'
    this.cbk && this.cbk(this.currentCount, this.countText)
  }

  _clock() {
    if (this.currentCount > 0) {
      this.currentCount--
    } else {
      this.stop()
    }
    this.countText = this.disabled ? `重新获取（${this.currentCount}）s` : '获取验证码'
    this.cbk && this.cbk(this.currentCount, this.countText)
  }

  start() {
    var that =this;
    if (this.disabled) {
      return false
    }
    this.disabled = true
    this.cbk && this.cbk(this.currentCount, this.countText)
    clearTimeout(this.timer)
    function countClock(){
      that._clock();
      that.timer = setTimeout(countClock, 1000)
    }
    countClock();
  }

  stop() {
    this._reset()
  }
}
//身份证隐藏
const formatIdcard = function (idcard) {
  if (idcard.length == 15) {
    return idcard.replace(/(\d{4})\d{8}(\d{3})/, "$1********$2");
  } else {
    return idcard.replace(/(\d{4})\d{8}(\d{3})/, "$1********$2");
  }
}
//防止多次跳转
const navigateStateChange = (self, disableKey) => {
  self.setData({
    [disableKey]: true
  })

  setTimeout(function () {
    self.setData({
      [disableKey]: false
    })
  }, 500)
}
module.exports = {
  formatTime: formatTime,
  formatDate: formatDate,
  getShoppingCartCount: getShoppingCartCount,
  addPVStat: addPVStat,
  afterPageLoad: afterPageLoad,
  processOrderData: processOrderData,
  processBannerImgLoad: processBannerImgLoad,
  processDecorationData: processDecorationData,
  processNavClick: processNavClick,
  getOrderStatus: getOrderStatus,
  numAddPreZero: numAddPreZero,
  formatImg: formatImg,
  convertItemLink: convertItemLink,
  drawPoster: drawPoster,
  tinyWxHeadImg: tinyWxHeadImg,
  autoGeyAddr: autoGeyAddr,
  phoneValidate,
  formatDateC,
  cusSubString,
  getCardSource,
  fetchSceneInfo,
  behaviorType,
  addBehaviorTrail,
  addRelation,
  chageChatData2,
  previewImageHkt,
  timestampToDayHkt,
  removeTokenIfExpired,
  fenToYuan,
  TimerClass,
  formatIdcard,
  navigateStateChange
}
